package com.lsk.mobile;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.lsk.util.ReturnData;
import com.lsk.util.Syslog;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/7/17 0017.
 */
public class MobileController extends Controller {
    Cache cache= Redis.use();
    static MobileServices mobileServices=new MobileServices();
    public void authorize(){
        String para=getPara();
        String orgId=getPara("orgId");
        String parentId=getPara("parentId");
        Record record=mobileServices.getWxConfigByOrgId(orgId,0);
        String redirectUrl=record.getStr("domain");
        String appId=record.getStr("appId");
        String url=SnsAccessTokenApi.getAuthorizeURL(appId,redirectUrl+"/mobile/authorizeCallBack",para,false);
        Record member=new Record();//会员的临时信息
        Syslog.info("跳转的路径为   "+url);
        member.set("orgId",orgId).set("parentId",parentId);
        cache.setex(para,60*10,member);
        redirect(url);
    }
    public void authorizeCallBack(){
        HttpSession session=getSession();
        String code=getPara("code");
        String state=getPara("state");
        Record member=cache.get(state);
        String orgId=member.getStr("orgId");
        String parentId=member.getStr("parentId");
        Record wxConfig=mobileServices.getWxConfigByOrgId(orgId,0);
        String appId=wxConfig.getStr("appId");
        String appsecret=wxConfig.getStr("appsecret");
        SnsAccessToken snsAccessToken=SnsAccessTokenApi.getSnsAccessToken(appId,appsecret,code);
        System.out.println(snsAccessToken.getJson());
        String access_token=snsAccessToken.getAccessToken();
        String openId=snsAccessToken.getOpenid();
        ApiResult apiResult=SnsApi.getUserInfo(access_token,openId);
        String unionId=apiResult.get("unionid");
        String heardUrl=apiResult.get("headimgurl");
        String nickname=apiResult.get("nickname");
        member.set("openId",openId);
        member.set("unionId",unionId);
        mobileServices.saveMember( openId, unionId, orgId,nickname,heardUrl,parentId);
        cache.setex(openId,60*60*24,member);
        session.setAttribute("openId",openId);
        redirect("/mobile/index");
    }

    /**
     * 去首页
     */
    public void index(){
        HttpSession session=getSession();
        String openId=session.getAttribute("openId").toString();
        Record record=cache.get(openId);
        String orgId=record.getStr("orgId");
        String unionId=record.getStr("unionId");
        List<Record> recordList=mobileServices.getCommodityList(orgId,unionId);
        setAttr("recordList",recordList);
        renderJsp("index1.jsp");
    }
    /**
     * 获取收货地址
     */
    public void getMemberAddress(){
        HttpSession session=getSession();
        String openId=session.getAttribute("openId").toString();
        Record record=cache.get(openId);

        String orgId=record.getStr("orgId");
        String unionId=record.getStr("unionId");
        ReturnData returnData=mobileServices.getMemberAddressService(unionId,orgId);
        renderJson(returnData);
    }


    /**
     * 发起支付
     */
    public void pay(){
        HttpSession session=getSession();
        String openId=session.getAttribute("openId").toString();
        Record record=cache.get(openId);
        String orgId=record.getStr("orgId");
        String unionId=record.getStr("unionId");
        String commodityId=getPara("commodityId");
        int number=getParaToInt("number");
        ReturnData returnData=mobileServices.payService(openId,orgId,unionId,commodityId,number);
        setAttr("returnData",returnData);
        renderJsp("pay.jsp");
    }
    @Clear
    public void callBack(){
        String message = "";
        try {
            String xmlMsg = HttpKit.readData(getRequest());
            Syslog.info("微信回调消息： " + xmlMsg);
            Map<String, String> map = PaymentKit.xmlToMap(xmlMsg);
            mobileServices.callBackService(map);
            message = "<xml> \n" +
                    "\n" +
                    "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                    "</xml> \n";
            Syslog.info("回信回调返回消息为 " + message);
        } catch (Exception e) {
            Syslog.error("回调异常" );
            Syslog.error(e);
            message = "<xml> \n" +
                    "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                    "</xml>";
        }
        renderJson(message);
    }
}
